package com.fenghuo.myviews;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;

import com.fenghuo.map.R;
import com.fenghuo.model.Histroy;
import com.fenghuo.utils.TimeUtil;
import com.fenghuo.utils.Utils;
import com.fenghuo.utils.Values;

import java.util.List;

/**
 * @author Administrator
 */
public class HistroyScrollView extends View implements View.OnTouchListener,
        OnGestureListener {

    private List<Histroy> data;// 数据
    private SparseArray<Bitmap[]> sparseArray;//推荐使用的
    private RectF[] rects;// 每个内容的高度 [用于点击事件]

    private Bitmap bmplocation;// 定位图标

    Paint mpaintk;// 空心
    Paint mpaints;// 实心
    Paint mpaintt;// 标题文字
    Paint mpaintc;// 内容文字
    Paint mpaintp;//地址
    Paint mpaintb;// 内容背景

    private GestureDetector gestureDetector;
    private Scroller mscroller;
    private OnContentClickListener contentClickListener;
    private boolean ispress = false;
    private int screenW, screenH;
    private int oneW;//屏幕宽度的 10分之1  【注：只能以全屏宽使用】
    private int imgW, imgH;//小图片


    public HistroyScrollView(Context context) {
        super(context);
        init(context);
    }

    public HistroyScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public HistroyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        setOnTouchListener(this);
        setLongClickable(true);
        mscroller = new Scroller(context, new DecelerateInterpolator());
        gestureDetector = new GestureDetector(this);

        mpaints = new Paint();
        mpaints.setColor(Color.parseColor("#65BFBD"));
        mpaints.setStyle(Style.FILL);
        mpaints.setStrokeWidth(Utils.getpx(getContext(), Utils.getpx(getContext(), 1.5f)));

        mpaintk = new Paint();
        mpaintk.setColor(Color.parseColor("#65BFBD"));
        mpaintk.setStyle(Style.STROKE);
        mpaintk.setStrokeWidth(Utils.getpx(getContext(), Utils.getpx(getContext(), 1.5f)));

        mpaintt = new Paint();
        mpaintt.setTextSize(Utils.getpx(getContext(), 17));

        mpaintc = new Paint();
        mpaintc.setTextSize(Utils.getpx(getContext(), 14));

        mpaintb = new Paint();
        mpaintb.setColor(Color.argb(100, 160, 220, 255));

        mpaintp = new Paint();
        mpaintp.setAlpha(160);
        mpaintp.setTextAlign(Align.RIGHT);
        mpaintp.setTextSize(Utils.getpx(getContext(), 12));

        rect = new Rect();
        rectb = new RectF();
        screenW = Utils.getScreenWidth(getContext());
        screenH = Utils.getScreenHeight(getContext());
        oneW = screenW / 10;
        imgW = oneW * 2;
        imgH = oneW * 4 / 3;
        contenRowH = gettextHeight(mpaintc);
        placeH = gettextHeight(mpaintp);
        titleRowH = gettextHeight(mpaintt);
        text_img = Utils.getpx(getContext(), 4);//文字、图片距离
        img_img = Utils.getpx(getContext(), 6);//图片-图片之间的距离
        img_radius = Utils.getpx(getContext(), 5);
        content_bottom = contenRowH;
        radius_s = Utils.getpx(getContext(), 6);
        radius_k = Utils.getpx(getContext(), 5);
        dp_1 = Utils.getpx(getContext(), 1);
        Options options = new Options();
        options.inSampleSize = (int) (13 / placeH);
        bmplocation = BitmapFactory.decodeResource(getResources(), R.drawable.dingwei, options);
    }

    private Rect rect;
    private RectF rectb;
    private int mtreeheight;// 总高度
    private int margintop = Utils.getpx(getContext(), 35);// 距离上面
    private float contenRowH;//内容高度
    private float placeH;//地址的高度
    private float titleRowH;//标题高度
    private float text_img;//文字、图片距离
    private float img_img;//图片-图片之间的距离
    private float img_radius;
    private float content_bottom;//下面的距离
    private float radius_s;
    private float radius_k;
    private float dp_1;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mtreeheight = margintop;
        // 画圆 、画标题
        if (data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                String content = data.get(i).getContent();
                int itemheight = 0;// 当前内容的高度
                // 计算、绘制文字
                int row = (int) Math.ceil(mpaintc.measureText(content) / (5.5f * oneW));//计算行数
                int count = mpaintc.breakText(content, 0, content.length(), true, 5.5f * oneW, null);// 一行的字数
                int start = 0;// 字符的开始位置
                if (content != null && !content.equals("")) {
                    for (int j = 0; j < row; j++) {
                        start = count * j;
                        int end = start + count > content.length() ? content.length() : start + count;
                        int rowx = (int) (3f * oneW);
                        int rowy = (int) (contenRowH * j + titleRowH * 2.4f + mtreeheight + placeH);//========文字距离标题起始为 2* titleRowH
                        canvas.drawText(content, start, end, rowx, rowy, mpaintc);// 【像素】
                    }
                }
                mtreeheight += (contenRowH * row + titleRowH * 2.4f);
                mtreeheight += text_img;// 文字、图片距离10【像素】
                itemheight = (int) (contenRowH * row + titleRowH * 2.4f + text_img);// 当前内容的高度
                mtreeheight += placeH * 2;
                itemheight += placeH;//地址的距离
                if (content != null || !content.equals("")) {
                    mtreeheight += content_bottom;
                    itemheight += content_bottom;
                }

                // 计算图片高度
                Bitmap[] bitmaps = null;
                if (data.get(i).getUrl() != null && !data.get(i).getUrl().equals("")) {
                    bitmaps = sparseArray.get(i);
                    if (bitmaps != null && bitmaps.length > 0) {
                        int imgrow = (int) Math.ceil((float) bitmaps.length / 2);
                        mtreeheight += (imgrow * imgH + (imgrow - 1) * img_img);
                        itemheight += (imgrow * imgH + (imgrow - 1) * img_img);
                    }
                }


                // 背景
                int backwidth = (content.equals("") && sparseArray.get(i) == null) ? 6 * oneW : (int) (9 * oneW);
                rectb.set((int) (2.4 * oneW), mtreeheight - itemheight + titleRowH, backwidth, mtreeheight - text_img);
                rects[i] = new RectF(rectb);
                canvas.drawRoundRect(rectb, img_radius, img_radius, mpaintb);
                if (ispress && position == i)
                    canvas.drawRoundRect(rectb, img_radius, img_radius, mpaintb);
                // 画图片
                if (bitmaps != null && bitmaps.length > 0) {
                    int imgrow = (int) Math.ceil((float) bitmaps.length / 2);// 图片行数
                    for (int j = 0; j < imgrow; j++) {
                        int imgrowcount = (j < imgrow - 1) ? 2 : (j + 1) * 2 == bitmaps.length ? 2 : 1;// 判断本行有几张图片
                        for (int j2 = 0; j2 < imgrowcount; j2++) {
                            int left = (int) (j2 == 0 ? 3 * oneW : 3 * oneW + imgW + img_img);// 图片开始的坐标
                            int top = (int) (mtreeheight - (imgrow + 1) * imgH - (imgrow - 1) * img_img + text_img);
                            int right = left + imgW;
                            int bottom = top + imgH;
                            rect.set(left, top, right, bottom);
                            canvas.drawBitmap(bitmaps[j * 2 + j2], null, rect, mpaintt);
                        }
                    }
                }

                // 写地址
                if (data.get(i).getUrl() != null && !data.get(i).getUrl().equals("") || content != null && !content.equals("")) {
                    int pend = mpaintt.breakText(data.get(i).getPlace(), true, getWidth() / 2, null);
                    float plenth = mpaintp.measureText(data.get(i).getPlace(), 0, pend);
                    canvas.drawBitmap(bmplocation, 8.6f * oneW - plenth - bmplocation.getWidth() - 3 * dp_1, mtreeheight - placeH * 3 / 2 - bmplocation.getHeight() + 2 * dp_1, null);
                    canvas.drawText((CharSequence) data.get(i).getPlace(), 0, pend, 8.6f * oneW, mtreeheight - placeH * 3 / 2, mpaintp);
                }

                // 画圆
                if (i % 2 == 0)
                    canvas.drawCircle(oneW, mtreeheight - itemheight, radius_k, mpaintk);
                else
                    canvas.drawCircle(oneW, mtreeheight - itemheight, radius_s, mpaints);
                // 画线
                canvas.drawLine(oneW, mtreeheight - itemheight + radius_k + dp_1 * 2, oneW, mtreeheight + content_bottom - radius_s - 3 * dp_1, mpaints);
                // 画标题
                canvas.drawText(data.get(i).getTitle(), (int) oneW * 1.28f, mtreeheight - itemheight + titleRowH / 2 - dp_1 * 2, mpaintt);
            }
        } else {

            canvas.drawLine(50, margintop - 10, getWidth() - 50,
                    margintop - 10, mpaints);
            canvas.drawText("暂无记录", 70, margintop + 20, mpaintt);
        }
    }

    /**
     * 初始化数据
     *
     * @param data
     */
    public void setData(List<Histroy> data) {
        this.data = null;
        this.sparseArray = null;
        this.rects = null;
        this.sparseArray = new SparseArray<Bitmap[]>();
        this.data = data;
        rects = new RectF[data.size()];
        // 初始化图片
        for (int i = 0; i < data.size(); i++) {
            Histroy histroy = data.get(i);
            String url = histroy.getUrl();
            if (url != null && !url.trim().equals("")) {
                String[] urls = url.split(",");
                Bitmap[] imgs = new Bitmap[urls.length];
                for (int k = 0; k < imgs.length; k++) {
                    Options opts = new Options();
                    opts.inSampleSize = 600 / imgW;
                    Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath() + Values.photo_Path + "/" + urls[k], opts);
                    if (bitmap == null) {
                        opts.inSampleSize = 141 / imgH;
                        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.noimg, opts);
                    }
                    imgs[k] = bitmap;
                }
                sparseArray.put(i, imgs);
            }
            String time = histroy.getTitle();
            if (time != null) {
                if (TimeUtil.getdatestr().equals(time)) {
                    histroy.setTitle("今天");
                } else if (TimeUtil.getday(-1).equals(time)) {
                    histroy.setTitle("昨天");
                } else {
                    if (time.length() > 6)
                        histroy.setTitle(time.substring(5, time.length()));
                }
            }
        }
    }

    public void setmBackColor(int color) {
        mpaintb.setColor(color);
        invalidate();
    }

    public void setmLineColor(int color) {
        mpaintk.setColor(color);
        mpaints.setColor(color);
        invalidate();
    }

    private int gettextHeight(Paint paint) {
        FontMetrics fm = paint.getFontMetrics();
        int height = (int) (Math.ceil(fm.descent - fm.ascent));
        return height;
    }


    int position = 0;// 点击的内容索引

    public void computeScroll() {
        if (mscroller.computeScrollOffset()) {
            scrollTo(mscroller.getCurrX(), mscroller.getCurrY());
            postInvalidate();
        }
    }

    ;

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN
                && event.getEdgeFlags() != 0) {
            return false;
        }
        gestureDetector.onTouchEvent(event);
        if (event.getAction() == MotionEvent.ACTION_UP) {
            ispress = false;
            invalidate();
        }
        return true;
    }

    /**
     * 得到绝对坐标
     *
     * @param positiony
     * @return
     */
    private int getAbsposition(int positiony) {
        return getScrollY() + positiony;
    }

    private void isCollision(MotionEvent e) {
        // [优化 这里的检测应该是只检测屏幕显示的部分]
        int downx = (int) e.getX();
        int downy = (int) e.getY();
        for (int i = 0; i < rects.length; i++) {
            int top = (int) rects[i].top;
            int right = (int) rects[i].right;
            int left = (int) rects[i].left;
            int bottom = (int) rects[i].bottom;
            if (downx > right || downx < left) {
                continue;
            } else if (getAbsposition(downy) < top
                    || getAbsposition(downy) > bottom) {
                continue;
            } else {// 点击了
                position = i;
                ispress = true;
                invalidate();
                break;
            }
        }
    }

    public void setOnContenClickListener(OnContentClickListener listener) {
        this.contentClickListener = listener;
    }

    public interface OnContentClickListener {
        void onclick(int posistion);
    }

    @Override
    public boolean onDown(MotionEvent e) {
//		System.out.println("=============onDown============");
        isCollision(e);//检测 是否按下内容
        if (!mscroller.isFinished()) {
            mscroller.abortAnimation();
        }
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
//		System.out.println("=============onShowPress============");
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
//		System.out.println("=============onSingleTapUp============");
        if (ispress && contentClickListener != null && data != null && data.size() > 0) {
            contentClickListener.onclick(position);
        }
//		ispress=false;
//		invalidate();
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                            float distanceY) {
//		System.out.println("=============onScroll============");
        if (distanceY < 0) {
            if (getScrollY() > 0) {
                scrollBy(0, (int) distanceY);
            }
        } else {
            if (getScrollY() <= mtreeheight - getHeight() + 100) {
                scrollBy(0, (int) distanceY);
            }
        }
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {
        System.out.println("=============onLongPress============");
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                           float velocityY) {
//		System.out.println("=============onFling============");
        mscroller.fling(0, getScrollY(), 0, (int) -velocityY, 0, 0, 0, mtreeheight - getHeight() + 100);
        invalidate();
        return false;
    }
}
